<template>
  <div>
    <div class="ha">
      <van-nav-bar title="购物车" fixed="true" left-arrow @click="bank" />
    </div>

    <div v-for="item in cars.data" :key="item">
      <div class="car-item">
        <van-checkbox
          class="car-check"
          v-model="item.checked"
          :value="item.name"
          @change="check(item)"
        ></van-checkbox>
        <van-image
          class="car-photo"
          style="float: left;"
          with="100%"
          heigth="100%"
          :src="item.photo"
        />
        <div class="car-text">
          <van-tag type="primary" class="car-inventory">库存:{{item.inventory-item.sales}}</van-tag>
          <div class="car-title">{{ item.name }}</div>
          <span class="car-specs">{{ item.specs }}，生产日期:{{item.birthday}}，保质期:{{item.expiryday}}天</span>
          <div style="font-size:10px;line-height:16px;color:gray;margin-top:2px;">
            <van-tag>{{item.supplier}}</van-tag>
          </div>
          <div class="car-explain">{{item.explain}}</div>
          <div
            class="car-price"
          >¥{{Math.round((item.isPromote==1?item.promotePrice:item.price)*100)/100}}</div>
          <div class="car-button">
            <div class="btn-reduce" v-if="item.carCount > 0" @click="reduce(item)">-</div>
            <div class="btn-number" v-if="item.carCount > 0">{{ item.carCount }}</div>
            <div class="btn-add" @click="add(item)">+</div>
          </div>
        </div>
      </div>
      <div class="car-action">
        <div class="checkAll">
          <van-checkbox v-model="isAll" @click="onChangeAll(cars.data)">全选</van-checkbox>
        </div>
        <div class="yixuan">已选 {{selectedCount}} 件</div>
        <div class="heji">
          合计:
          <label style="font-size:14px;color:red;font-weight:bold;">¥{{selectedSum}}</label>
        </div>
        <div class="xiadan" @click="submitOrder">提交订单</div>
      </div>
    </div>
  </div>
</template>

<script>
import { useRouter } from "vue-router";
import { reactive, toRefs, onMounted } from "vue";
import { showToast, showConfirmDialog } from "vant";
import { generateOrder } from "../../api/order";
export default {
  setup() {
    const router = useRouter();
    const data = reactive({
      cars: {
        total: 0,
        sum: 0,
        data: []
      },
      isAll: true,
      selectedCount: 0,
      selectedSum: 0,
      check:[]
    });

    const events = {
      submitOrder() {
        if (data.selectedCount === 0) {
          showToast("请先选择要下单的商品");
          return;
        }
        showConfirmDialog({
          title: "提示",
          message: `订单总金额￥${data.selectedSum},确认下单吗?`,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          confirmButtonColor: "#green"
        })
          .then(() => {
            let orders = [];
            data.cars.data.forEach(d => {
              if (d.checked) {
                orders.push({
                  gid: d.id,
                  number: d.carCount
                });
              }
            });
            generateOrder({
              orders: orders
            }).then(res => {
              if (res.result === 0) {
                showToast("操作成功");
                for (let i = 0; i < data.cars.data.length; i++) {
                  if (data.cars.data[i].checked) {
                    data.cars.data.splice(i, 1);
                    i--;
                    continue;
                  }
                }
                if (data.cars.data.length === 0) {
                  localStorage.removeItem("cart");
                } else {
                  localStorage.setItem("cart", JSON.stringify(data.cars));
                }
                setTimeout(() => {
                  router.push("/order");
                }, 500);
              }
            });
            // 点击确认按钮后执行的操作
          })
          .catch(() => {
            // 点击取消按钮后执行的操作
          });
      },
      onChangeAll(val) {
        if (data.isAll) {
          val.forEach(d => {
            d.checked = true;
          });
        } else {
          val.forEach(d => {
            d.checked = false;
          });
        }
      },
      add(val) {
        let inventory = val.inventory - val.sales;
        if (val.carCount >= inventory) {
          showToast("库存不足");
          return;
        }

        let car = data.cars.data.find(d => d.id == val.id);
        if (car === undefined) {
          val.carCount = 1;
          data.cars.data.push(val);
        } else {
          val.carCount++;
        }
        data.cars.total++;
        let price =
          Math.round(
            (val.isPromote === 1 ? val.promotePrice : val.price) * 100
          ) / 100; //总价
        data.cars.sum = Math.round((data.cars.sum + price) * 100) / 100;

        data.cars.data.forEach(d => {
          if (d.checked === true && d.id === val.id) {
            data.selectedCount += 1;
            let selectedSum =
              1 * (d.isPromote === 1 ? d.promotePrice : d.price);
            data.selectedSum =
              Math.round((data.selectedSum + selectedSum) * 100) / 100;
          }
        });
        localStorage.setItem("cart", JSON.stringify(data.cars));
      },
      reduce(val) {
        let car = data.cars.data.find(d => d.id == val.id);

        if (car.carCount <= 1) {
          for (let i = 0; i < data.cars.data.length; i++) {
            if (data.cars.data[i].id === car.id) {
              let selectedSum =
                1 *
                (data.cars.data[i].isPromote == 1
                  ? data.cars.data[i].promotePrice
                  : data.cars.data[i].price);
              data.selectedSum = data.selectedSum - selectedSum;
              data.selectedSum = Math.round(data.selectedSum * 100) / 100;
              data.selectedCount -= 1;
              data.cars.data.splice(i, 1);
              break;
            }
          }
        }
        data.cars.total--;
        val.carCount--;
        let sun = val.isPromote === 1 ? val.promotePrice : val.price;
        data.cars.sum -= Math.round(sun * 100) / 100;
        data.cars.sum = Math.round(data.cars.sum * 100) / 100;
        localStorage.setItem("cart", JSON.stringify(data.cars));
        data.cars.data.forEach(d => {
          if (d.checked === true && d.id === val.id) {
            data.selectedCount -= 1;
            let selectedSum =
              Math.round(
                1 * (d.isPromote == 1 ? d.promotePrice : d.price) * 100
              ) / 100;
            data.selectedSum =
              Math.round((data.selectedSum - selectedSum) * 100) / 100;
            data.selectedSum = Math.round(data.selectedSum * 100) / 100;
          }
        });
        if (data.cars.data.length === 0) {
          showToast("购物车已清空");
          setTimeout(() => {
            router.go("-1");
          }, 500);
        }
      },
      check(val) {
        let check = [];
        if (!val.checked) {
          data.cars.data.forEach(d => {
            if ((d.id = val.id)) {
              data.check.push(d.checked);
            }
          });
          data.isAll = false;
          data.selectedCount -= val.carCount;
          let selectedSum =
            val.carCount * (val.isPromote == 1 ? val.promotePrice : val.price);
          data.selectedSum -= Math.round(selectedSum * 100) / 100;
          data.selectedSum = Math.round(data.selectedSum * 100) / 100;
        } else {
          data.cars.data.forEach(d => {
            if ((d.id = val.id)) {
              check.push(d.checked);
            }
          });
          for (let i = 0; i < check.length; i++) {
            if (check[i] == false) {
              data.isAll = false;
            } else {
              data.isAll = true;
            }
          }
          data.selectedCount += val.carCount;
          let selectedSum =
            val.carCount * (val.isPromote == 1 ? val.promotePrice : val.price);
          data.selectedSum =
            data.selectedSum + Math.round(selectedSum * 100) / 100;
        }
      },
      //返回
      bank() {
        router.go(-1);
      }
    };
    onMounted(() => {
      let cars = JSON.parse(localStorage.getItem("cart"));
      if (cars) {
        cars.data.forEach(d => {
          data.cars.total += d.carCount;
          data.cars.sum +=
            (d.isPromote === 1 ? d.promotePrice : d.price) * d.carCount;
          d.checked = true;
        });
        data.cars.data = cars.data;
        data.selectedCount = data.cars.total;
        data.selectedSum = Math.round(data.cars.sum * 100) / 100;
      }
    });
    return {
      ...events,
      ...toRefs(data)
    };
  }
};
</script>

<style scoped>
.yixuan {
  position: absolute;
  left: 100px;
}

.heji {
  position: absolute;
  left: 170px;
}

.xiadan {
  width: 80px;
  height: 30px;
  background-color: #ee0a24;
  color: #fff;
  position: absolute;
  right: 20px;
  text-align: center;
  line-height: 30px;
  top: 15px;
  border-radius: 30px;
}
.checkAll {
  position: absolute;
  top: 20px;
  left: 10px;
  font-size: 12px;
}
.car-action {
  position: fixed;
  bottom: 0px;
  width: 100%;
  height: 60px;
  line-height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  font-size: 12px;
}
.car-button {
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: flex;
}

.btn-add {
  width: 17px;
  height: 17px;
  background-color: red;
  color: #fff;
  text-align: center;
  line-height: 15px;
  border-radius: 20px;
  font-weight: bold;
}

.btn-reduce {
  width: 17px;
  height: 17px;
  background-color: red;
  color: #fff;
  text-align: center;
  line-height: 15px;
  border-radius: 20px;
  font-weight: bold;
}

.btn-number {
  margin-left: 10px;
  margin-right: 10px;
  text-align: center;
  font-size: 12px;
}
.car-price {
  font-size: 16px;
  font-weight: bold;
  color: red;
  position: absolute;
  bottom: 3px;
}
.car-explain {
  font-size: 10px;
  color: gray;
  line-height: 18px;
  overflow: hidden;
  text-overflow: ellipsis;
}
.car-specs {
  font-size: 10px;
  color: gray;
  line-height: 16px;
}
.car-inventory {
  position: absolute;
  right: 5px;
  top: 0px;
}
.car-item {
  position: relative;
  display: flex;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  border-radius: 5px;
  margin: 5px;
}
.car-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 20px;
}
.car-text {
  padding-left: 10px;
}
.car-check {
  position: relative;
  /* top: 40px; */
}
.car-photo {
  width: 80px;
  height: 80px;
  border: 1px solid #eee;
  padding: 2px;
  border-radius: 5px;
  margin-left: 30px;
}
.exam-container {
  margin: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  padding: 10px;
  border-radius: 5px;
  display: flex;
}
.ha {
  /* height: calc(100vh - 100px); */
  overflow: auto;
  line-height: 50px;
  /* margin-top: 50px; */
  height: 50px;
}
</style>